$(document).ready(function () {
    function getPath(obj) {
        var url = null;
        // 下面函数执行的效果是一样的，只是需要针对不同的浏览器执行不同的 js 函数而已
        if (window.createObjectURL != undefined) { // basic
            url = window.createObjectURL(obj);
        } else if (window.URL != undefined) { // mozilla(firefox)
            url = window.URL.createObjectURL(obj);
        } else if (window.webkitURL != undefined) { // webkit or chrome
            url = window.webkitURL.createObjectURL(obj);
        }
        return url;
    }

    //验证登录
    $.ajax({
        type: "GET",
        url: "load",
        dataType: "json",
        data: {},
        timeout: 10000,
        async: false,
        cache: false,
        success: function (res) {
            if (res.result != "yes") {
                window.location.href = "login";
            }
        }
    });
    //预览图片
    $("#picture").change(function () {
        var path = getPath(this.files[0]);
        $("#picContent").html('<img src="' + path + '" alt="图片预览失败" id="preview"/>');
    });
    $("#submit").click(function () {
        var form = new FormData();
        var title = $("#title").val();
        var tag = $("#tag").val();
        var price = $("#price").val();
        var detail = $("#detail").val();
        var picture = document.getElementById("picture").files[0];
        if (title == null || tag == null || price == null || detail == null || picture == null) {
            alert("所有项都必须填写");
            return;
        }
        form.append("title", title);
        form.append("tag", tag);
        form.append("price", price);
        form.append("detail", detail);
        form.append("picture", picture);

        $.ajax({
            type: "POST",
            url: "index/good/publish",
            data: form,
            // 告诉jQuery不要去处理发送的数据
            processData: false,
            // 告诉jQuery不要去设置Content-Type请求头
            contentType: false,
            success: function (result) {
                if (result.result == "SUCCESS") {
                    alert("发布成功");
                    window.location.href="index";
                } else {
                    alert(result.reason);
                }
            }
        });
        /*
        $("#goodForm").ajaxForm({
            type: "POST",
            url: "index/good/publish",
            dataType: "json",
            data: {},
            forceSync: true,
            timeout: 5000,
            cache: false,
            success: function (result) {
                if (result.result == "SUCCESS") {
                    alert("发布成功");
                } else {
                    alert(result.reason);
                }
            }
        });*/
    });
    $("#home").click(function () {
       window.location.href = "index";
    });
});